﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace FranceTriple.Dal
{
    public class ForumDal
    {
        public static Forum GetEntity(int entityID)
        {
            Forum forum;

            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    forum = (from f in ctx.ForumSet
                             where (f.Id == entityID)
                             select f).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("RetrieveError".ToLocalizedString(), "Forum", ex.Message), ex) { EntityType = typeof(Forum) };
            }
            return forum;
        }

        public static Int32 GetForumIdByCategoryId(int CategoryId)
        {
            Int32 forumId;

            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    forumId = (from c in ctx.ForumCategorySet.Include("Forum")
                               where (c.Id == CategoryId)
                               select c.Forum.Id).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("RetrieveError".ToLocalizedString(), "GetForumIdByCategoryId", ex.Message), ex) { EntityType = typeof(Forum) };
            }
            return forumId;
        }

        public static int CreateEntity(Forum entity, List<aspnet_RolesForumSet> roleForums)
        {
            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    foreach (Forum f in ctx.ForumSet.Where(f1 => f1.OrderForum >= entity.OrderForum))
                    {
                        f.OrderForum = f.OrderForum + 10;
                    }
                    Forum forum = new Forum();
                    forum.LabelForum = entity.LabelForum;
                    forum.OrderForum = entity.OrderForum;
                    ctx.AddToForumSet(forum);

                    if (roleForums != null)
                    {
                        aspnet_RolesForumSet newRoleForum;

                        foreach (aspnet_RolesForumSet roleForum in roleForums)
                        {
                            newRoleForum = new aspnet_RolesForumSet();
                            newRoleForum.Forum_Id = forum.Id;
                            newRoleForum.ForumSet = forum;

                            newRoleForum.Role_Id = roleForum.Role_Id;
                            newRoleForum.RightLevel = roleForum.RightLevel;
                            newRoleForum.aspnet_Roles = (aspnet_Role)ctx.GetObjectByKey(roleForum.aspnet_Roles.EntityKey);

                            forum.aspnet_RolesForumSet.Add(newRoleForum);
                        }
                    }
                    ctx.SaveChanges();
                    return forum.Id;
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("InsertError".ToLocalizedString(), "Forum", ex.Message), ex) { EntityType = typeof(Forum) };
            }
        }

        public static void UpdateEntity(Forum entity, List<aspnet_RolesForumSet> roleForums)
        {
            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    var forumToUpdate = ctx.ForumSet.Include("aspnet_RolesForumSet").Where(f => f.Id == entity.Id).FirstOrDefault();
                    if (forumToUpdate == null)
                    {
                        CreateEntity(entity, null);
                        return;
                    }

                    if (forumToUpdate.OrderForum != entity.OrderForum)
                    {
                        //Utiliser la place libérée par le déplacement
                        foreach (Forum f in ctx.ForumSet)
                        {
                            if (f.OrderForum > forumToUpdate.OrderForum)
                                f.OrderForum = f.OrderForum - 10;
                        }
                        //Décaler à partir de la nouvelle position pour créer une place
                        foreach (Forum f in ctx.ForumSet)
                        {

                            if (f.OrderForum >= entity.OrderForum)
                                f.OrderForum = f.OrderForum + 10;
                        }
                    }

                    forumToUpdate.LabelForum = entity.LabelForum;
                    forumToUpdate.OrderForum = entity.OrderForum;

                    if (roleForums != null)
                    {
                        aspnet_RolesForumSet newRoleForum;

                        forumToUpdate.aspnet_RolesForumSet.Clear();
                        ctx.SaveChanges();

                        foreach (aspnet_RolesForumSet roleForum in roleForums)
                        {
                            newRoleForum = new aspnet_RolesForumSet();
                            newRoleForum.Forum_Id = forumToUpdate.Id;
                            newRoleForum.ForumSet = forumToUpdate;

                            newRoleForum.Role_Id = roleForum.Role_Id;
                            newRoleForum.RightLevel = roleForum.RightLevel;
                            newRoleForum.aspnet_Roles = (aspnet_Role)ctx.GetObjectByKey(roleForum.aspnet_Roles.EntityKey);

                            forumToUpdate.aspnet_RolesForumSet.Add(newRoleForum);
                        }
                    }
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("UpdateError".ToLocalizedString(), "Forum", ex.Message), ex) { EntityType = typeof(Forum) };
            }
        }

        public static void DeleteEntity(int entityID)
        {
            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    var forumToUpdate = ctx.ForumSet.Where(f => f.Id == entityID).FirstOrDefault();
                    if (forumToUpdate == null)
                        return;

                    foreach (Forum f in ctx.ForumSet)
                    {
                        if (f.OrderForum > forumToUpdate.OrderForum)
                            f.OrderForum = f.OrderForum - 10;
                    }

                    ctx.ForumSet.DeleteObject(forumToUpdate);
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("DeleteError".ToLocalizedString(), "Forum", ex.Message), ex) { EntityType = typeof(Forum) };
            }
        }

        public static Forum[] GetEntities(string searchText)
        {
            Forum[] res;

            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    res = (from c in ctx.ForumSet
                           where c.LabelForum.Contains(searchText)
                           orderby c.OrderForum, c.LabelForum
                           select c).ToArray();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("RetrieveError".ToLocalizedString(), "Forum", ex.Message), ex) { EntityType = typeof(Forum) };
            }
            return res;
        }
    }
}
